package com.homeinns.server.controller;

import com.homeinns.server.constant.CookieConstant;
import com.homeinns.server.constant.RedisConstant;
import com.homeinns.server.dataobject.UserInfo;
import com.homeinns.server.enums.ResultEnum;
import com.homeinns.server.enums.RoleEnum;
import com.homeinns.server.service.UserInfoService;
import com.homeinns.server.utils.CookieUtil;
import com.homeinns.server.utils.ResultVOUtil;
import com.homeinns.server.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/login",name = "用户登录模块")
public class UserInfoRestController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping(value = "/buyer")
    public ResultVO buyerLogin(@RequestParam("openid") String openid, HttpServletResponse response){

        UserInfo user = userInfoService.findByOpenid(openid);
        if (user == null) {
            return ResultVOUtil.error(ResultEnum.LOGIN_FAIL);
        }
        if(RoleEnum.BUYER.getCode()!=user.getRole()){
            return ResultVOUtil.error(ResultEnum.ROLE_ERROR);
        }
        CookieUtil.set(response, CookieConstant.OPENID,openid,CookieConstant.EXPIRE);
        return ResultVOUtil.success();
    }

    @GetMapping(value = "/seller", name = "卖家登录")
    public ResultVO seller(@RequestParam("openid") String openid, HttpServletRequest request, HttpServletResponse response){

        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(null!=cookie&& StringUtils.isEmpty(redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_TEMPLATE,cookie.getValue())))){
            return ResultVOUtil.success();
        }
        UserInfo userInfo = userInfoService.findByOpenid(openid);
        if(null==userInfo){
            return ResultVOUtil.error(ResultEnum.LOGIN_FAIL);
        }
        if(RoleEnum.SELLER.getCode()!=userInfo.getRole()){
            return ResultVOUtil.error(ResultEnum.ROLE_ERROR);
        }
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_TEMPLATE,token), openid, CookieConstant.EXPIRE, TimeUnit.SECONDS);

        CookieUtil.set(response, CookieConstant.TOKEN, token, CookieConstant.EXPIRE);
        return ResultVOUtil.success();
    }

}
